const { request } = require('../../utils/api');

Page({
  data: {
    username: '',
    password: '',
    isAgree: false
  },

  onUsernameInput: function(e) {
    this.setData({
      username: e.detail.value
    });
  },

  onPasswordInput: function(e) {
    this.setData({
      password: e.detail.value
    });
  },

  // 处理登录成功后的跳转
  handleLoginSuccess: function(userData) {
    // 保存登录状态和token
    wx.setStorageSync('isLoggedIn', true);
    wx.setStorageSync('token', userData.token);
    wx.setStorageSync('userInfo', userData.user);

    // 显示登录成功提示
    wx.showToast({
      title: '登录成功',
      icon: 'success',
      duration: 1500,
      complete: () => {
        // 在提示显示完成后进行跳转
        setTimeout(() => {
          // 使用switchTab跳转到首页
          wx.switchTab({
            url: '/pages/index/index',
            success: () => {
              console.log('跳转成功');
            },
            fail: (error) => {
              console.error('跳转失败', error);
              // 如果switchTab失败，尝试使用redirectTo
              wx.redirectTo({
                url: '/pages/index/index',
                fail: (err) => {
                  console.error('redirectTo也失败了', err);
                  wx.showToast({
                    title: '跳转失败，请重试',
                    icon: 'none'
                  });
                }
              });
            }
          });
        }, 1500);
      }
    });
  },

  onLogin: function() {
    if (!this.data.isAgree) {
      wx.showToast({
        title: '请先同意用户协议和隐私政策',
        icon: 'none'
      });
      return;
    }

    if (!this.data.username || !this.data.password) {
      wx.showToast({
        title: '请输入账号和密码',
        icon: 'none'
      });
      return;
    }

    // 显示加载提示
    wx.showLoading({
      title: '登录中...',
      mask: true
    });

    // 调用登录接口
    request('/api/login', {
      method: 'POST',
      data: {
        username: this.data.username,
        password: this.data.password
      }
    }).then(response => {
      wx.hideLoading();
      if (response.success) {
        console.log('登录成功，原始用户信息:', response.user);
        // 存储用户信息
        const userInfo = {
          id: parseInt(response.user.id),  // 确保id是数字类型
          username: response.user.username,
          nickname: response.user.nickname
        };
        console.log('存储的用户信息:', userInfo);
        wx.setStorageSync('userInfo', userInfo);
        wx.showToast({
          title: '登录成功',
          icon: 'success',
          duration: 2000
        });
        setTimeout(() => {
          wx.switchTab({
            url: '/pages/index/index',
            success: () => {
              console.log('跳转到首页成功');
            },
            fail: (error) => {
              console.error('跳转到首页失败:', error);
            }
          });
        }, 2000);
      } else {
        wx.showToast({
          title: response.message || '登录失败',
          icon: 'none'
        });
      }
    }).catch(error => {
      wx.hideLoading();
      console.error('登录失败:', error);
      wx.showToast({
        title: error.message || '登录失败，请重试',
        icon: 'none'
      });
    });
  },

  onWechatLogin: function() {
    if (!this.data.isAgree) {
      wx.showToast({
        title: '请先同意用户协议和隐私政策',
        icon: 'none'
      });
      return;
    }

    wx.showToast({
      title: '微信登录功能开发中',
      icon: 'none'
    });
  },

  onAgreementChange: function(e) {
    this.setData({
      isAgree: e.detail.value.length > 0
    });
  },

  onShowUserAgreement: function() {
    wx.showModal({
      title: '用户协议',
      content: '这里是用户协议内容...',
      showCancel: false
    });
  },

  onShowPrivacyPolicy: function() {
    wx.showModal({
      title: '隐私政策',
      content: '这里是隐私政策内容...',
      showCancel: false
    });
  },

  onGoToRegister: function() {
    wx.navigateTo({
      url: '/pages/register/register'
    });
  }
}); 